package lpg.tool.optionpg;

import java.util.Map;
import java.util.TreeMap;
import lpg.util.Utility;

class PathElement
{
    PathElement(String path)
    {
        this.path = path;
    }

    void merge(PathElement element)
    {
        int length = Utility.prefixMatch(path, element.path);

        PathElement newBranchElement = null;
        PathSet newBranch = null;
        if (element.path.length() > length)
        {
            // New branch at position length
            newBranchElement = new PathElement(element.path.substring(length));

            newBranch = new PathSet();
            newBranch.elemMap.put(element.path.charAt(length), newBranchElement);
        }
        for (Map.Entry<Integer, PathSet> entry : element.branchSet.entrySet())
        {
            int prefixLength = entry.getKey();
            PathSet branch = entry.getValue();
            if (prefixLength <= length)
            {
                // Merge with old branch
                mergeBranch(prefixLength, branch);
            }
            else
            {
                // Add to new branch
                newBranchElement.branchSet.put(prefixLength - length, branch);
            }
        }
        if (newBranch != null)
        {
            mergeBranch(length, newBranch);
        }
    }

    private void mergeBranch(int length, PathSet newBranch)
    {
        PathSet branch = branchSet.get(length);
        if (branch == null)
        {
            branchSet.put(length, newBranch);
        }
        else
        {
            branch.merge(newBranch);
        }
    }

    int getSingleBranchPrefixLength()
    {
        if (branchSet.size() == 1)
        {
            return branchSet.keySet().iterator().next();
        }
        return 0;
    }

    String getSingleBranchPath()
    {
        if (branchSet.size() == 1)
        {
            return branchSet.values().iterator().next().getSingleElementPath();
        }
        return null;
    }

    String toString(String indent, int prefixLength)
    {
        StringBuilder buf = new StringBuilder();
        buf.append("\n");
        buf.append(indent);
        if (prefixLength > 0)
        {
            buf.append(prefixLength);
            buf.append(":");
        }
        buf.append("[");
        buf.append(path);
        buf.append("]");

        for (Map.Entry<Integer, PathSet> entry : branchSet.entrySet())
        {
            buf.append(entry.getValue().toString(indent + "    ", entry.getKey()));
        }
        return new String(buf);
    }

    final String path;
    final Map<Integer, PathSet> branchSet = new TreeMap<Integer, PathSet>();

}
